/**
 * Author: Ravi Tamada
 * URL: www.androidhive.info
 * twitter: http://twitter.com/ravitamada
 * */
package com.madev.isellcrazyitems;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.madev.isellcrazyitems.entity.User;
import com.madev.isellcrazyitems.handler.DatabaseHandler;
import com.madev.sales.R;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

public class RegisterActivity extends Activity {
	Button btnRegister, dateBtn;
	Button btnLinkToLogin;
	EditText inputFullName;
	EditText inputEmail;
	EditText inputPassword, inputRetypePassword, inputAddress;
	TextView registerErrorMsg, nameErrorMsg, emailErrorMsg, passwordErrorMsg, retypeErrorMsg, addressErrorMsg, dobErrorMsg, dateTV, dobTV;
	
	int year, month, day;
	Calendar c1;
	
	// JSON Response node names
	/*
	private static String KEY_SUCCESS = "success";
	private static String KEY_ERROR = "error";
	private static String KEY_ERROR_MSG = "error_msg";
	private static String KEY_UID = "uid";
	private static String KEY_UNIQUEID = "uniqueID";
	private static String KEY_NAME = "name";
	private static String KEY_EMAIL = "email";
	private static String KEY_CREATEDATE = "createDate";
	private static String KEY_UPDATEDATE = "updateDate";
	*/
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		
		dateBtn = (Button)findViewById(R.id.dateBtn);
		dateTV = (TextView)findViewById(R.id.dateTV);

		dateBtn.setOnClickListener(new OnClickListener() {
			  
			   @Override
			public void onClick(View v) {
				   
				   DatePickerDialog DPD = new DatePickerDialog(RegisterActivity.this, mDateSetListener, year, month, day);
				   
				   // Setting Min+Max Date
				   
				   Calendar cal = Calendar.getInstance();
				   cal.add(Calendar.YEAR, -18);
				   Date d = cal.getTime();
				   
				   DPD.getDatePicker().setMaxDate(d.getTime());
				   
				   cal = Calendar.getInstance();
				   cal.add(Calendar.YEAR, -120);
				   
				   d = cal.getTime();
				   
				   DPD.getDatePicker().setMinDate(d.getTime());

				   
				   DPD.show();
			                    
			   }
		});
		
		 
		  final Calendar c = Calendar.getInstance();
		  year = c.get(Calendar.YEAR);
		  month = c.get(Calendar.MONTH);
		  day = c.get(Calendar.DAY_OF_MONTH);
		 
		// Importing all assets like buttons, text fields
		inputFullName = (EditText) findViewById(R.id.registerName);
		inputEmail = (EditText) findViewById(R.id.registerEmail);
		inputPassword = (EditText) findViewById(R.id.registerPassword);
		inputRetypePassword = (EditText) findViewById(R.id.retypePassword);
		inputAddress = (EditText) findViewById(R.id.registerAddress);
		btnRegister = (Button) findViewById(R.id.btnRegister);
		btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
				
		nameErrorMsg = (TextView) findViewById(R.id.name_error); 
		//nameErrorMsg.setVisibility(View.GONE);
		emailErrorMsg = (TextView) findViewById(R.id.email_error);  
		passwordErrorMsg = (TextView) findViewById(R.id.password_error); 
		retypeErrorMsg = (TextView) findViewById(R.id.retype_error);  
		addressErrorMsg = (TextView) findViewById(R.id.address_error);
		dobErrorMsg = (TextView) findViewById(R.id.dob_error); 
		registerErrorMsg = (TextView) findViewById(R.id.register_error);
		
		
		// Register Button Click event
		btnRegister.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View view) {
				String name = inputFullName.getText().toString();
				String email = inputEmail.getText().toString();
				String password = inputPassword.getText().toString();
				String retype = inputRetypePassword.getText().toString();
				String address = inputAddress.getText().toString();
				String dob = dateTV.getText().toString();
				
				boolean valid = true;
				
				// Name Validation
				if (name.equals("") || name.equals(null) || name.length() < 6)
				{
					nameErrorMsg.setVisibility(0);
					nameErrorMsg.setText("Please provide your Full Name");
					valid = false;
				}
				else
				{
					nameErrorMsg.setVisibility(View.GONE);
					Log.e("NAME", "valid");
				}
				
				// Email Validation
				if (email.equals("") || email.equals(null) || email.length() < 3)
				{
					emailErrorMsg.setVisibility(0);
					emailErrorMsg.setText("Please provide your Email");
					valid = false;
				}
				else if (!isEmailValid(email))
				{
					emailErrorMsg.setVisibility(0);
					emailErrorMsg.setText("Email is in invalid format");
					valid = false;
				}
				else
				{
					emailErrorMsg.setVisibility(View.GONE);
				}
				
				// Password Validation
				if (password.equals("") || password.equals(null))
				{
					passwordErrorMsg.setVisibility(0);
					passwordErrorMsg.setText("Password is required");
					valid = false;
				}
				else if (password.length() < 3)
				{
					passwordErrorMsg.setVisibility(0);
					passwordErrorMsg.setText("Password is too short");
					valid = false;
				}
				else
				{
					passwordErrorMsg.setVisibility(View.GONE);
				}
				
				// retype Validation
				if (password.equals("") || password.equals(null))
				{
					retypeErrorMsg.setVisibility(View.GONE);
					retypeErrorMsg.setText("Please retype your password");
				}
				else if (!retype.equals(password))
				{
					retypeErrorMsg.setVisibility(0);
					retypeErrorMsg.setText("Password does not match");
					valid = false;
				}
				else if(retype.equals(password))
				{
					retypeErrorMsg.setVisibility(View.GONE);
				}
				
				// Address Validation
				if (address.equals("") || address.equals(null) || address.length() < 3)
				{
					addressErrorMsg.setVisibility(0);
					addressErrorMsg.setText("Please provide your address");
					valid = false;
				}
				else
				{
					addressErrorMsg.setVisibility(View.GONE);
				}
				
				// DOB Validation
				if (dob.equals("") || dob.equals(null) || dob.length() < 3)
				{
					dobErrorMsg.setVisibility(0);
					dobErrorMsg.setText("Please provide your dob");
					valid = false;
				}
				else
				{
					dobErrorMsg.setVisibility(View.GONE);
				}
				
				
				if (valid)
				{
					//UserFunctions userFunction = new UserFunctions();
					//JSONObject json = userFunction.registerUser(name, email, password, address, dob);
					
					DatabaseHandler  uDb = new DatabaseHandler (getApplicationContext());
					User u = new User(name, email, password, address, dob, "customer");
					
					registerErrorMsg.setVisibility(2);
					registerErrorMsg.setText("");
					if(uDb.addUser(u))
					{
						// user successfully registered
						// Store user details in SQLite Database
						DatabaseHandler ldb = new DatabaseHandler(getApplicationContext());
						ldb.logoutUser();
						ldb.addLogin(u);						
						
						// Launch Dashboard Screen
						Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
						// Close all views before launching Dashboard
						dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(dashboard);
						// Close Registration Screen
						finish();
					}
					else
					{
						// Error in registration
						registerErrorMsg.setVisibility(0);
						registerErrorMsg.setText("Error occured in registration");
					}
				}
				else{
					// Error in registration
					registerErrorMsg.setText("There are errors in this form");
				}
				

			}
		});

		// Link to Login Screen
		btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent i = new Intent(getApplicationContext(),
						LoginActivity.class);
				startActivity(i);
				// Close Registration View
				finish();
			}
		});
	}
	
	 @Override
	 @Deprecated
	 protected void onPrepareDialog(int id, Dialog dialog) {
	  // TODO Auto-generated method stub
	  super.onPrepareDialog(id, dialog);
	 
	  
	  
	  ((DatePickerDialog) dialog).updateDate(year, month, day);
	 }


	 private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		 
		  @Override
		public void onDateSet(DatePicker view, int year1, int monthOfYear,
		    int dayOfMonth) {
		   year = year1;
		   month = monthOfYear;
		   day = dayOfMonth;		   
		   
		   
		   c1 = Calendar.getInstance();
		   c1.set(year, month, day);
		   
		   updateDisplay();
		  }
	 };
		 
	 private void updateDisplay() {
	  // TODO Auto-generated method stub
	  /*
		 dateTV.setText(new StringBuilder()
	    // Month is 0 based so add 1
	    .append(month + 1).append("-").append(day).append("-")
	    .append(year));
	  */
		 
	
	  SimpleDateFormat stringFormat = new SimpleDateFormat("yyyy-MM-dd");
	  SimpleDateFormat numFormat = new SimpleDateFormat("dd MMMM yyyy");

	  dateTV.setText(stringFormat.format(c1.getTime()));
	  dateBtn.setText(numFormat.format(c1.getTime()));
	  
	  
	 }
	 
	 public boolean isEmailValid(String email)
	    {
	         String regExpn =
	             "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
	                 +"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
	                   +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
	                   +"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
	                   +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
	                   +"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";

	     CharSequence inputStr = email;

	     Pattern pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE);
	     Matcher matcher = pattern.matcher(inputStr);

	     if(matcher.matches())
	        return true;
	     else
	        return false;
	}
	
}
